<template lang="pug">
  .page
    .AccountsReceivableManage
      .search-form.mb-10.pl-10.pr-10
        Form.ivu-row(ref="formData" :model="formData" :label-width="100")
          FormItem.form-item.ivu-col.pr-20.mb-15(v-for="(item, index) of formItem" :label="item.label" :key="index" :class="item.style")
            template(v-if="item.type === 'input'")
              Input( v-model="formData[item.model]" :placeholder="item.placeholder" clearable)
            template(v-if="item.type === 'interval-input'" style="display:flex;flex-direction:row;")
              Input.pull-left.interval-date-140(style="display:inline-block;width:150px" v-model="formData[item.model1]" :placeholder="item.placeholder1" clearable)
              span.pl-10.pr-10.pull-left.line-h-32 -- 
              Input.pull-left.interval-date-140(style="display:inline-block;width:150px" v-model="formData[item.model2]" :placeholder="item.placeholder2" clearable)
            template(v-if="item.type === 'interval'")
              DatePicker.pull-left.interval-date-140(v-model="formData[item.model1]" :value="datePickerDefault" :placeholder="item.placeholder1" @on-change="handleChangeDatePicker")
              span.pl-10.pr-10.pull-left.line-h-32 --
              DatePicker.pull-left.interval-date-140(v-model="formData[item.model2]" :value="datePickerDefault" :placeholder="item.placeholder2" @on-change="handleChangeDatePicker")
            template(v-if="item.type === 'button'")
              Button(type="info" @click="searchFn") 查询

      .pl-20.pr-20.bg-white
        Table.hasTitle-table.beautiful-table(:columns="thead" :data="tableData" :stripe="true" ref="demoTable"
          @on-selection-change="handleOnSelectChange"
        )
          .clearfix.pr-24.pl-12.overflow-hidden(slot="header")
            .table-title-lefttxt.pull-left
              |合计
              span.text-info.pl-5.pr-5.font-weight {{tableComone.totalRows}}
              |条
            .pull-right.table-title-btns
              Button.mr-10(v-if="hasImport" size="small" type="info" @click="handleShowBatchImportModal") 批量导入
              Button.mr-10(v-if="hasExport" size="small" type="info" @click="exportBtn") 导出
              Button.mr-10(v-if="mergeBtn" size="small" type="info" @click="mergeFn") 合并明细
              Button(v-if="delBtn" size="small" type="error" @click="delFn") 删除
          .clearfix.pl-20.pr-20(slot="footer")
            Page(
              :total="tableComone.totalRows"
              @on-change="onChangePage"
              @on-page-size-change="onpageSizeChange"
              show-sizer
              show-total
              placement="top"
              prev-text="上一页"
              next-text="下一页"
              :page-size-opts="[10, 20, 30, 50, 100]"
            )
      BatchImportModal(ref="BatchImportModal" @query="searchFn")</template>

<script>
import moment from 'moment'
import { Common } from '@/utils/common.js'
import { FinanceReimburseApi } from '@/api/FinanceReimburse.api.js'
import { ExpenseManageListThead } from './tableHead.js'
import _cloneDeep from 'clone-deep'
import { EmployeesApi } from '@/api/Employees.api.js'
import dataApi from '@/api/data.js'
import { setTimeout } from 'timers';
import BatchImportModal from './modal/BatchImportModal.vue'
// import expandRow from './table-expand.vue'
import config from '@/config'
const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro.replace('/api', '/')

export default {
  name: 'expenseManageList',

  components: {
    BatchImportModal
  },

  data () {
    return {
      companyId: '', // 公司ID
      companyName: '', // 公司名称
      employeeId: '', // 员工ID
      thead: _cloneDeep(ExpenseManageListThead),
      tableData: [],
      formData: {
        payBank: null,
        MinAmount: null,
        MaxAmount: null,
        BeginTime: null,
        EndTime: null
      },
      formItem: [
        { type: 'interval', label: '报销日期：', placeholder1: '开始日期', prop1: 'BeginTime', model1: 'BeginTime', placeholder2: '结束日期', prop2: 'EndTime', model2: 'EndTime', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-12 ivu-col-span-xxl-8' },
        { type: 'input', label: '支付银行：', placeholder: '请输入支付银行', prop: 'PayBank', model: 'PayBank',style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-12 ivu-col-span-xxl-8' },
        { type: 'interval-input', label: '报销金额：', placeholder1: '报销最小金额', prop1: 'MinAmount', model1: 'MinAmount', placeholder2: '报销最大金额', prop2: 'MaxAmount', model2: 'MaxAmount', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-12 ivu-col-span-xxl-8' },
        { type: 'button', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-12 ivu-col-span-xxl-8' }
      ],
      rules: {
        IdCardNo: [
          { type: 'string', message: '请输入正确的身份证号码', pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/ }
        ]
      },
      selectedEmployeeId: [], // 勾选的id集合,array格式
      selectedEmployeeArr: [], // 勾选的id, name数组集合
      tableComone: {
        pageIndex: 1, // 页码
        totalRows: 0, // 总条数
        pageSize: 10, // 当前页面展示条数
        total: 0, // 应付总计
      },
      downLoadRul: '',
      arrListDown: {
        securityNos: [],
        statusOps: [
        ],
        payAccount: [],
        PayType: []
      },
      datePickerDefault: new Date(), // 当前时间
      importExcel: {
        uploadLoading: false,
        progressPercent: 0,
        showProgress: false,
        showRemoveFile: false,
        file: null
      },
      isDelete: false
    }
  },

  watch: {
  },
  computed: {
    actionArr () {
      let arr = this.$store.state.user.actionAccess.map(item => {
        return item.code
      })
      return arr
    },
    // 查询
    hasFind () {
      return this.actionArr.indexOf('Find') > -1
    },
    // 导入
    hasImport () {
      return this.actionArr.indexOf('Import') > -1
    },
    // 导出
    hasExport () {
      return this.actionArr.indexOf('Export') > -1
    },
    // 合并明细
    mergeBtn () {
      return this.actionArr.indexOf('Merge') > -1
    },
    // 删除
    delBtn () {
      return this.actionArr.indexOf('Delete') > -1
    }
  },

  mounted () {
    this.query()
  },

  methods: {

    // 获取付款账号
    async getPayAccount () {
      var params = {
        HasPaging: true,
        PageIndex: 1,
        PageSize: 5000,
        Status: 1
      }
      let res = await FinancePayAccountApi.getList(params)
      console.log('获取付款账号res: ', res)
      if (res.status === 200 && res.data.success) {
        this.arrListDown.payAccount = []
        res.data.data.map(item => {
          this.arrListDown.payAccount.push({label: item.unitName, value: item.id, bankName: item.bankName, accountNo: item.accountNo})
        })
      } else {
        this.arrListDown.payAccount = []
      }
    },

    // 合并明细
    mergeFn () {
      if (this.selectedEmployeeId.length) {
        FinanceReimburseApi.merge({
          IDs:this.selectedEmployeeId
        }).then(res => {
          if (res.data.success) {
            this.$Message.success('合并成功！')
            this.searchFn()
          } else {
            this.$Message.error(res.data.message)
          }
        })
      } else {
        this.$Message.warning('请选择需要合并的条目')
      }
    },

    // 删除
    delFn () {
      if (this.selectedEmployeeId.length) {
        this.$Modal.confirm({
          title: '确定删除？',
          content: '<p>删除后不可撤销！</p>',
          onOk: () => {
            FinanceReimburseApi.Delete({
              IDs:this.selectedEmployeeId
            }).then(res => {
              if (res.data.success) {
                this.$Message.success('删除成功！')
                this.searchFn()
              } else {
                this.$Message.error(res.data.message)
              }
            })
          },
          onCancel: () => {
          }
        })
      } else {
        this.$Message.warning('请选择需要删除的条目')
      }
    },

    // 搜索
    searchFn () {
      this.tableComone.pageIndex = 1
      this.selectedEmployeeId = []
      this.query()
    },

    /**
     * 分页页码变动
     * @param {Number} val pageIndex
     */
    onChangePage (val) {
      this.tableComone.pageIndex = val
      this.query()
    },
    /**
     * 分页页码变动
     * @param {Number} val pageSize
     */
    onpageSizeChange (val) {
      this.tableComone.pageIndex = 1
      this.tableComone.pageSize = val
      this.query()
    },
    /**
     * 分页查询接口
     * @param {Object} obj {pageIndex, pageSize}
     */
    async query () {
      var params = {
        HasPaging: true,
        PageIndex: this.tableComone.pageIndex,
        PageSize: this.tableComone.pageSize,
        IsApply: true
      }
      this.formData.BeginTime = this.formData.BeginTime? moment(this.formData.BeginTime).format('YYYY-MM-DD') : ''
      this.formData.EndTime = this.formData.EndTime? moment(this.formData.EndTime).format('YYYY-MM-DD') : ''
      let res = await FinanceReimburseApi.getList({...params, ...this.formData})
      console.log('应付res: ', res)
      if (res.status === 200 && res.data.success) {
        this.tableData = res.data.data
        this.tableComone.totalRows = res.data.totalRows
        this.tableComone.total = res.data.total
      } else {
        this.tableData = []
      }
      this.loading = false
    },

    handleShowBatchImportModal () {
      this.$refs.BatchImportModal.show()
    },

    // 表格选择操作
    handleOnSelectChange (value) {
      this.selectedEmployeeArr = value.map((item) => {
        return { id: item.id, name: item.name }
      })
      this.selectedEmployeeId = value.map((item) => {
        return item.id
      })
      console.log('列表勾选数组1', this.selectedEmployeeArr)
      console.log('列表勾选数组2', this.selectedEmployeeId)
    },

    // 日期选择
    handleChangeDatePicker (val) {
      console.log('val: ', val)
      // this.formData.salaryMonth = val
      // this.getDayList()
    },

    handleMaxSizeTen () {
      this.$Message.error({
        content: '您上传的文件太大，上传文件大小不能超过10M',
        duration: 10,
        closable: true
      })
    },
    importBtn () {
      this.$refs.BatchImportModal.openModal()
    },
    // 导出
    async exportBtn () {
      // console.log(this.selectedEmployeeId)
      this.formData.BeginTime = this.formData.BeginTime? moment(this.formData.BeginTime).format('YYYY-MM-DD') : ''
      this.formData.EndTime = this.formData.EndTime? moment(this.formData.EndTime).format('YYYY-MM-DD') : ''
      var params = {
        PageIndex: this.tableComone.pageIndex,
        PageSize: this.tableComone.pageSize,
        IDs: this.selectedEmployeeId,
        ...this.formData
      }
      let res = await FinanceReimburseApi.export(params)
      if (res.status === 200 && res.data.success) {
        console.log('❤ 返回链接: ', baseUrl + res.data.message)
        window.open(baseUrl + res.data.message, '_blank')
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

  } // methods end
}
</script>

<style lang="less" scoped>

</style>
